package com.example.wzh.rxdemo;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.wzh.rxdemo.databinding.FragmentOperatorBinding;
import com.example.wzh.rxdemo.rx.MyObserver;
import com.wzh.advancelog.log.WzhLog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.functions.Supplier;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class OperatorFragment extends Fragment {
    FragmentOperatorBinding binding;
    CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    public View onCreateView(@androidx.annotation.NonNull LayoutInflater inflater, ViewGroup container
            , Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_operator, container, false);
        return binding.getRoot();
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(OperatorFragment.this)
                        .navigate(R.id.action_operator_to_business);
            }
        });
        initOperators();
    }

    private List<String> operators;

    private void initOperators() {
        operators = new ArrayList<>();
        operators.add("create");
        operators.add("defer");
        operators.add("empty");
        operators.add("never");
        operators.add("throw");
        operators.add("from");
        operators.add("interval");
        operators.add("just");
        operators.add("range");
        operators.add("repeat");
        operators.add("start");
        operators.add("timer");
        OperatorAdapter adapter = new OperatorAdapter(operators);
        binding.rcv.setLayoutManager(new GridLayoutManager(getContext(), 4));
        binding.rcv.setAdapter(adapter);
        binding.rcv.addItemDecoration(new RecyclerSpace(4, Color.GRAY, RecyclerSpace.STYLE_WITH_EDGE));
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View ItemView, int position) {
                performOperator(operators.get(position));
            }
        });
    }

    private void performOperator(String s) {
        switch (s) {
            //创建型
            case "create":
                performCreate();
                break;
            case "defer":
                performDefer();
                break;
            case "empty":
                performEmpty();
                break;
            case "never":
                performNever();
                break;
            case "throw":
                performThrow();
                break;
            case "from":
                performFrom();
                break;
            case "interval":
                performInterval();
                break;
            case "just":
                performJust();
                break;
            case "range":
                performRange();
                break;
            case "repeat":
                performRepeat();
                break;
            case "start":
                performStartMy();
                break;
            default:
                break;
        }
    }


    private void performStartMy() {
        //reactX中的start在RxJava3中体现为fromFuture,FromCallable
        Observable.fromFuture(Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(2000);
                return 2;
            }
        })).subscribe(new MyObserver<Integer>(compositeDisposable) {
            @Override
            public void onNext(@NonNull Integer integer) {
                WzhLog.i(LogTag.TAG_WZH, "thread:" + Thread.currentThread().getName() + " integer:"
                        + integer);
            }
        });
    }

    int repeatCount = 0;

    private void performRepeat() {
        Observable.range(1, 4).repeatWhen(new Function<Observable<Object>, ObservableSource<?>>() {
            @Override
            public ObservableSource<?> apply(Observable<Object> objectObservable) {
                return objectObservable.takeWhile(new Predicate<Object>() {
                    @Override
                    public boolean test(Object o) {
                        repeatCount++;
                        return repeatCount < 3;
                    }
                });
            }
        }).subscribe(new MyObserver<>(compositeDisposable));
    }

    private void performRange() {
        Observable.range(9, 14).subscribe(new MyObserver<>(compositeDisposable));
    }

    private void performJust() {
        //Just类似于From，但是From会将数组或Iterable的数据取出然后逐个发射，而Just只是简单的原样发射，将数组或Iterable当做单个数据。
        ArrayList<Integer> integerList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        Observable.just(integerList).subscribe(new MyObserver<>(compositeDisposable));
    }

    private void performInterval() {
        //这里订阅是在主线程，发射数据是在io线程
        Observable.interval(500, TimeUnit.MILLISECONDS, Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) {
                WzhLog.i(LogTag.TAG_WZH, "thread:" + Thread.currentThread().getName());
            }
        }).take(7).subscribe(new MyObserver<Long>(compositeDisposable) {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                WzhLog.i(LogTag.TAG_WZH, "thread:" + Thread.currentThread().getName());
            }

            @Override
            public void onNext(@NonNull Long aLong) {
                WzhLog.i(LogTag.TAG_WZH, "thread:" + Thread.currentThread().getName() + " data:" + aLong);
            }
        });
    }

    private void performFrom() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        Observable.fromIterable(integerList).subscribe(new MyObserver<>(compositeDisposable));
    }

    private void performThrow() {
        Observable.just(1, 2, 3, 4, 5).flatMap(new Function<Integer, ObservableSource<?>>() {
            @Override
            public ObservableSource<?> apply(Integer integer) {
                if (integer > 3) {
                    return Observable.error(new Supplier<Throwable>() {
                        @Override
                        public Throwable get() {
                            return new Exception("自定义异常");
                        }
                    });
                } else {
                    return Observable.just(integer);
                }
            }
        }).subscribe(new MyObserver<Object>(compositeDisposable) {
            @Override
            public void onError(@NonNull Throwable e) {
                WzhLog.i(LogTag.TAG_WZH, e.getMessage());
                //即使flatMap转换过的每个Observable都可能观测到异常，但是铺平的时候还是只发射一个
            }
        });
    }

    private void performNever() {
        Observable.just(1, 2, 3, 4, 5).flatMap(new Function<Integer, ObservableSource<?>>() {
            @Override
            public ObservableSource<?> apply(Integer integer) {
                if (integer > 3) {
                    return Observable.never();
                } else {
                    return Observable.just(integer);
                }
            }
        }).subscribe(new MyObserver<>(compositeDisposable));
    }

    private void performEmpty() {
        Observable.just(1, 2, 3, 4, 5).flatMap(new Function<Integer, ObservableSource<Integer>>() {
            @Override
            public ObservableSource<Integer> apply(Integer integer) {
                if (integer > 3) {
                    return Observable.empty();
                } else {
                    return Observable.just(integer);
                }
            }
        }).subscribe(new MyObserver<>(compositeDisposable));
    }

    private void performDefer() {
        Observable.defer(new Supplier<ObservableSource<EventA>>() {
            @Override
            public ObservableSource<EventA> get() {
                return Observable.just(new EventA());
            }
        }).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) {
                WzhLog.i(LogTag.TAG_WZH, "subscribe");
            }
        }).subscribe(new MyObserver<EventA>(compositeDisposable) {
            @Override
            public void onNext(@NonNull EventA eventA) {
                WzhLog.i(LogTag.TAG_WZH, "eventA consume");
            }
        });
    }

    private void performCreate() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) {
                emitter.onNext("create onNext");
            }
        }).subscribe(new MyObserver<>(compositeDisposable));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
    }
}